# -*-coding:utf-8-*-
import json, requests, os, time, requests
from redis import StrictRedis

def get_data(url, params, headers):
	send_data = json.dumps(params)
	request = requests.post(url, data=send_data, headers=headers, verify=False)
	response = request.json()
	result = dict(response)
	return result['return'][0]

def save_salt_token(salt_api, username, password):
	headers = {"Content-type": "application/json"}
	login_url = os.path.join(salt_api, 'login')
	login_params = {'username': username, 'password': password, 'eauth': 'pam'}
	res = get_data(login_url, login_params, headers)
	result = dict()
	result['token'] = res['token']
	result['expire'] = res['expire']
	r.set('salttoken', result)
	return result

r = StrictRedis.from_url('redis://192.168.132.129:6379/2')
if r.exists('salttoken'):
	result = eval(r.get('salttoken'))
	print result
	if result['expire'] >  time.time():
		print result['token']
	else:
		token = save_salt_token('https://47.92.113.93:8001/', 'saltapi', 'ADsfsf787SKFLNHffsas145')
		r.set('salttoken', token)
else:
	token = save_salt_token('https://47.92.113.93:8001/', 'saltapi', 'ADsfsf787SKFLNHffsas145')
	r.set('salttoken', token)


